/* cl.ext.fileinput 0.1*/
(
    function (factory) {
        if (typeof define === 'function' && define.amd) {
            define(['jquery',"FileInput"], factory);
        } else if (typeof module === 'object' && module.exports) {
            module.exports = function( root, jQuery ) {
                var fileInputjs = require('FileInput');
                if ( jQuery === undefined ) {
                    if ( typeof window !== 'undefined' ) {
                        jQuery = require('jquery');
                    }
                    else {
                        jQuery = require('jquery')(root);
                    }
                }
                factory(jQuery);
                return jQuery;
            };
        } else {
            factory(jQuery);
        }
    }(
    function ($){
        var defaultExtInfo = {isShowLoading:true,isUploadBase64:true,multipleBtnName: "批量上传文件", fileType: "jpg,png", checkData: [],clickCallback:null,isCheckExt:true};
        var defaults={
            initShowType:"previewFile", //previewFile| buttonFile | multiple
            buttonFileName:"上传文件",
            buttonFileCls:"btn-grayLight",
            "style": "well",
            "btn_change": null,
            "no_icon": 'ace-icon fa fa-picture-o',
            "allowExt": ["jpeg", "jpg", "png"],
            "allowMime": ["image/jpg", "image/jpeg", "image/png"],
            "droppable": true,
            "thumbnail": "fit",
            "whType":"equal",
            "showFileName": false,
            "beforeRemoveCallback":null,
            "checkCallback":null,
            "ajaxInfoCallback":null,
            "tipmsg_top":"",
            "tipmsg_bottom":"",
            "maxSize":false,
            "imgSrcUrl":false,
            "sizeWidth":0,
            "sizeHeight":0,
            "spanWidth":0,
            "infoExt":defaultExtInfo,
            "successCallback":null
        };
        var defaultsMime={
            "jpg":["image/jpg","image/jpeg","image/pjpeg"],
            "jpe":["image/jpg","image/jpeg","image/pjpeg"],
            "jpeg":["image/jpg","image/jpeg","image/pjpeg"],
            "png":["image/png","image/x-png"],
            "gif":["image/gif"],
            "bmp":["image/bmp"],
            "ico":["image/x-icon"],
            "mp3":["audio/mpeg"],
            "mid":["audio/midi"],
            "ogg":["audio/ogg"],
            "mp4a":["audio/mp4"],
            "wav":["audio/wav"],
            "wma":["audio/x-ms-wma"],
            "3gp":["video/3gpp"],
            "avi":["video/x-msvideo"],
            "asf":["video/x-ms-asf"],
            "dv":["video/x-dv"],
            "mov":["video/quicktime"],
            "mp4":["video/mp4"],
            "mpg4":["video/mp4"],
            "mpeg":["video/mpeg"],
            "mpg":["video/mpeg"],
            "ra":["audio/x-pn-realaudio"],
            "ram":["audio/x-pn-realaudio"],
            "rmvb":["video/vnd.rn-realvideo"],
            "wm":["video/x-ms-wmv"],
            "wmv":["audio/x-ms-wmv"],
            "wmx":["video/x-ms-wmx"],
            "flv":["video/x-flv"],
            "mkv":["video/x-matroska"],
            "txt":["text/plain"],
            "rar":["application/x-rar-compressed"],
            "zip":["application/zip","application/x-zip-compressed"]
        };
        var defaultsSuffix={
            "jpg":["jpg","jpe","jpeg"],
            "png":["png"],
            "gif":["gif"],
            "bmp":["bmp"],
            "ico":["ico"],
            "mp3":["mp3"],
            "mid":["mid"],
            "ogg":["ogg"],
            "mp4a":["mp4a"],
            "wav":["wav"],
            "wma":["wma"],
            "3gp":["3gp"],
            "avi":["avi"],
            "asf":["asf"],
            "dv":["dv"],
            "mov":["mov"],
            "mp4":["mp4"],
            "mpg4":["mpg4"],
            "mpeg":["mpeg"],
            "mpg":["mpg"],
            "ra":["ra"],
            "ram":["ram"],
            "rmvb":["rmvb"],
            "wm":["wm"],
            "wmv":["wmv"],
            "wmx":["wmx"],
            "flv":["flv"],
            "mkv":["mkv"],
            "txt":["txt"],
            "zip":["zip"]
        };
        var defaultsImg=["jpg","jpe","jpeg","png","gif","bmp","ico"];
        var $modalCommon={
            getDefaults :function () {
                return defaults
            },
            getOptions : function (elementData,options) {
                var self=this;
                options=$.ExtCommon.isCheckEmpty(options)?{}:options;
                var optionBase =$.ExtCommon.initMergeJson(elementData,options);
                optionBase =$.ExtCommon.initMergeJson(this.getDefaults(),optionBase);
                if(optionBase.initShowType==="previewFile" || optionBase.initShowType==="buttonFile"){
                    optionBase.maxSize=$.ExtCommon.isCheckEmpty(optionBase.maxSize)?false:optionBase.maxSize;
                    optionBase.imgSrcUrl=$.ExtCommon.isCheckEmpty(optionBase.imgSrcUrl)?false:optionBase.imgSrcUrl;
                    var fileImgType=self.getImgType(optionBase.infoExt.fileType);
                    optionBase.isImgType=fileImgType.length>0;
                    optionBase.infoExt.fileType=optionBase.isImgType?fileImgType.join(","):optionBase.infoExt.fileType;
                    optionBase.no_icon=optionBase.isImgType? 'ace-icon fa fa-picture-o':'ace-icon fa fa-cloud-upload';
                    optionBase.allowExt=self.getAllowExt(optionBase.infoExt.fileType);
                    optionBase.allowMime=self.getAllowMime(optionBase.allowExt);
                    optionBase.isImgType = optionBase.initShowType === "buttonFile" ? false : optionBase.isImgType;
                    optionBase.isUseBase64 = optionBase.infoExt.isUploadBase64 ? optionBase.isImgType : false;
                    if(optionBase.beforeRemoveCallback){
                        optionBase.before_remove=function(obj){
                            if(optionBase.beforeRemoveCallback){optionBase.beforeRemoveCallback(obj)}
                            return true
                        };
                    }
                    if(optionBase.ajaxInfoCallback){
                        var ajaxUrl=optionBase.ajaxInfoCallback.url;
                        var ajaxPara=$.ExtCommon.isCheckEmpty(optionBase.ajaxInfoCallback.data)?{}:optionBase.ajaxInfoCallback.data;
                        if (optionBase.isUseBase64) {
                            optionBase.ajaxCallback= function (file, imgbase64, cb) {
                                $.ExtAjax.initLoadStart(optionBase.animateLoading);
                                var para={imageBase64Str: imgbase64};
                                if(!$.ExtCommon.isCheckEmpty(ajaxPara)){
                                    para =$.ExtCommon.initMergeJson(ajaxPara,para);
                                }
                                $.ExtAjax.initPost({
                                    url: ajaxUrl,
                                    contentType: "application/x-www-form-urlencoded",
                                    data: para,
                                    successCallback: function (res) {
                                        if (res.success) {
                                            if(optionBase.ajaxInfoCallback.success){
                                                var aa=optionBase.ajaxInfoCallback.success(file.$element,res.data)
                                            }
                                            if (cb) cb();
                                        } else {
                                            $.ExtNotify.error(res.msg);
                                        }
                                        optionBase.animateLoading.dataListLength=1;
                                        $.ExtAjax.initLoadEnd(optionBase.animateLoading);
                                    }
                                });
                            }
                        }else{
                            optionBase.ajaxCallback= function (selfFile, filedata, cb,path) {
                                var formData = new FormData();
                                if(filedata.length){
                                    if(filedata.length>1){
                                        for(var f=0;f<filedata.length;f++){
                                            formData.append("file["+f+"]",filedata[f]);
                                        }
                                    }else{
                                        formData.append("file",filedata[0]);
                                        if(path){ formData.append("url",path);}
                                    }
                                }else{
                                    formData.append("file",filedata);
                                    if(path){ formData.append("url",path);}
                                }
                                $.ExtAjax.initPost({
                                    url: ajaxUrl,
                                    data: formData,
                                    cache: false,
                                    processData: false,
                                    contentType: false,
                                    successCallback: function (res) {
                                        if(selfFile.optionModal.infoExt.hideLoadCallback){selfFile.optionModal.infoExt.hideLoadCallback()}
                                        if (res.success) {
                                            if(optionBase.ajaxInfoCallback.success){
                                                var aa=optionBase.ajaxInfoCallback.success(selfFile.$element,res.data)
                                            }
                                            if (cb) cb();
                                        } else {
                                            $.ExtNotify.error(res.msg);
                                        }
                                    }
                                });
                            }
                        }
                    }
                    if($.ExtCommon.isCheckEmpty(optionBase.checkCallback)) {
                        optionBase.checkCallback = function (obj, err) {
                            if (err.length > 0) {
                                $.ExtNotify.error(err.join("<br />"));
                            }
                        };
                    }
                }
                else if(optionBase.initShowType==="multiple"){
                    self.convertCheckData(optionBase.infoExt.checkData);
                }
                return optionBase
            },
            convertCheckData:function(data){
                var self=this;
                $.each(data,function (i,info) {
                    var fileImgType=self.getImgType(info.fileType);
                    info.isImgType=fileImgType.length>0;
                    info.fileType=info.isImgType?fileImgType.join(","):info.fileType;
                    info.allowExt=self.getAllowExt(info.fileType);
                    info.allowMime=self.getAllowMime(info.allowExt);
                });
            },
            getImgType:function(type){
                var arrType=type.split(",");
                return $.map(arrType,function(info){if(defaultsImg.indexOf(info)>-1){return info;}});
            },
            getAllowExt:function(type){
                var arr=type.split(",");
                var arrExt=$.map(arr,function(info){return defaultsSuffix[info]?defaultsSuffix[info]:[]});
                return $.ExtCommon.getArrUnique(arrExt)
            },
            getAllowMime:function(ext){
                var arrMime=$.map(ext,function(info){return defaultsMime[info]?defaultsMime[info]:[]});
                return $.ExtCommon.getArrUnique(arrMime)
            },
            getButtonFileHtml:function(btnName,cls){
                return '<div class="panel-btn-file"><button class="btn '+cls+' waves-effect " type="button">'+
                    '<i class="fa fa-cloud-upload"></i><span>'+btnName+'</span>'+
                    '</button></div>';
            }
        };
        var modalOperateElement=function(element,options){
            this.$element=element;
            this.elementModal ={};
            this.elementModal.parent=element.parent();
            this.optionModal=options;
        };
        modalOperateElement.prototype = {
            init: function () {
                var self=this;
                self.bindEvent();
                if(self.optionModal.infoExt.isShowLoading){
                    self.optionModal.infoExt.hideLoadCallback=function(){
                        self.hideLoad();
                    }
                }
            },
            bindEvent:function(){
                var self=this;
                if (self.optionModal.ajaxCallback) {
                    self.$element.off("change").on("change", function(){
                        if(self.optionModal.infoExt.isCheckExt) {
                            if (self.checkFile(this.files)) {
                                self.showLoad();
                                self.optionModal.ajaxCallback(self, this.files, null,null,$(this).val());
                                self.reset();
                            }
                        }else {
                            self.showLoad();
                            self.optionModal.ajaxCallback(self, this.files, null,null,$(this).val());
                            self.reset();
                        }
                    });
                }
                if (self.optionModal.infoExt.clickCallback) {
                    self.$element.off("click").on("click", function(event){
                        var check=self.optionModal.infoExt.clickCallback();
                        if(!check){
                            event.stopPropagation();
                            event.preventDefault();
                            return false;
                        }
                    });
                }
            },
            showLoad:function () {
                if(this.elementModal.parent.children(".loader-inner").length===0){
                    this.elementModal.parent.append('<div class="loader-inner ball-clip-rotate"><div></div></div>')
                }
                var elBody=$("body");
                if(elBody.children(".btn-file-loader-bg").length===0){
                    elBody.append('<div class="btn-file-loader-bg modal-backdrop fade in"></div>')
                }
            },
            hideLoad:function () {
                this.elementModal.parent.children(".loader-inner").remove();
                $("body").children(".btn-file-loader-bg").remove();
            },
            checkFile:function (files) {
                var hasFile = 'File' in window;
                var allowExt = $.ExtCommon.getFileExtRegex(this.optionModal.allowExt);
                var allowMime = $.ExtCommon.getFileMimeRegex(this.optionModal.allowMime);
                var maxSize = this.optionModal.maxSize ? this.optionModal.maxSize * 1024 : false;
                if (!(allowExt || allowMime || maxSize)) return true;
                var file = files[0];
                var filename = !hasFile ? file : file.name;
                var errExt = allowExt && !allowExt.test(filename) ? 1 : 0;
                var errMime = 0;
                if (hasFile) {
                    var type = $.trim(file.type);
                    if (type.length > 0 && allowMime && !allowMime.test(type)) {
                        errMime = 1
                    }
                }
                var errSize = maxSize && file.size > maxSize ? 1 : 0;
                var arrErrMsg = [];
                if (errExt > 0 || errMime > 0) arrErrMsg.push("上传文件类型不正确");
                if (errSize > 0) arrErrMsg.push("上传文件大小不正确");
                if (this.optionModal.checkCallback) {
                    if(arrErrMsg.length>0){this.reset()}
                    this.optionModal.checkCallback(this.element, arrErrMsg)
                }
                return arrErrMsg.length === 0;
            },
            reset:function () {
                this.$element.wrap('<form>').parent().get(0).reset();
                this.$element.unwrap();
            },
            destroyHtml:function(){
                this.$element.parent().empty().remove();
                this.$element=null;
            }
        };
        var UploadFileExtModal = function(element, options) {
            var self=this;
            self.element = $(element);
            self.optionBase=$modalCommon.getOptions(self.element.data(),options);
            switch(self.optionBase.initShowType){
                case "previewFile":
                    var elBase=$('<div class="box-file-base"></div>');
                    self.element.before(elBase);
                    self.element.appendTo(elBase);
                    if(self.optionBase.infoExt.isShowLoading){
                        elBase.addClass("datajsonload");
                        self.element.wrap("<div></div>");
                        self.optionBase.animateLoading={place: "box", boxId: self.element, height: "auto", type: "circle"};
                    }
                    self.element.ace_file_input(self.optionBase);
                    break;
                case "buttonFile":
                    var p=$($modalCommon.getButtonFileHtml(self.optionBase.buttonFileName,self.optionBase.buttonFileCls));
                    self.element.before(p);
                    self.element.appendTo(p);
                    self.elementOperate=new modalOperateElement(this.element,this.optionBase);
                    self.elementOperate.init();
                    break;
                case "multiple":
                    var mp=$($modalCommon.getButtonFileHtml(self.optionBase.infoExt.multipleBtnName));
                    self.element.before(mp);
                    self.element.appendTo(mp);
                    self.elementMultipleInfo=self.element.ExtFileMultiple(self.optionBase.infoExt);
                    break;

            }
        };
        UploadFileExtModal.prototype = {
            init:function(){},
            destroy:function(){},
            changeCheckData:function(data){
                if(this.optionBase.initShowType==="multiple"){
                    $modalCommon.convertCheckData(data);
                    this.optionBase.infoExt.checkData=data;
                    if(this.elementMultipleInfo){this.elementMultipleInfo.changeCheckData(data);}
                }
            },
            disabled:function (isDisabled) {
                this.element.prop("disabled", isDisabled);
                this.element.parent().prop("disabled", isDisabled);
            }
        };
        $.fn.ExtUploadFile = function(options) {
            var dataFun;
            this.each(function() {
                var el = $(this);
                var tempData=el.data('ExtUploadFile');
                if (tempData) {
                    if (typeof  options === "string") {
                        if (tempData[options]) {
                            dataFun =tempData[options]()
                        } else {
                            dataFun = tempData
                        }
                    } else {
                        dataFun = tempData
                    }
                } else {
                    dataFun = new UploadFileExtModal(el, options);
                    el.data('ExtUploadFile', dataFun);
                }
            });
            return dataFun;
        };
        return UploadFileExtModal;
    })
);
